<template>
    <div class="cardContent">
        <a-button type="primary" @click="openLeaveDraw">我要请假</a-button>
        <a-table :dataSource="leaveBillList"
                 :columns="columns"
                 :pagination="false"
                 style="margin-top: 10px"
                 bordered>
            <template #bodyCell="{text,record,index,column}">
                <template v-if="column.key == 'status'">
                    <a-tag v-if="text == 0" color="processing">
                        <template #icon>
                            <sync-outlined :spin="true"/>
                        </template>
                        审批中
                    </a-tag>
                    <a-tag v-if="text == 1" color="success">
                        <template #icon>
                            <check-circle-outlined/>
                        </template>
                        审批通过
                    </a-tag>
                    <a-tag v-if="text == 2" color="error">
                        <template #icon>
                            <close-circle-outlined/>
                        </template>
                        被驳回
                    </a-tag>
                </template>
                <template v-if="column.key == 'leaveDate'">
                    {{formatDate(text)}}
                </template>
                <a-space v-if="column.key == 'action'">
                    <a-popconfirm
                            title="删除数据无法恢复，请确认是否删除？"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button v-if="record.status == 1" type="danger">删除</a-button>
                    </a-popconfirm>
                    <a-button type="primary"
                              @click="checkAuditTrail(record.id)">
                        查看审核记录
                    </a-button>
                </a-space>
            </template>
        </a-table>
        <a-config-provider :locale="locale">
            <a-pagination style="margin-top: 10px; text-align: right"
                          v-model:current="pagination.current"
                          v-model:pageSize="pagination.pageSize"
                          show-quick-jumper
                          show-size-changer
                          :total="pagination.total"
                          :show-total="total => `总 ${total} 条数据`"
                          :page-size-options="pageSizeOptions"
                          @change="onChange"/>
        </a-config-provider>
    </div>
    <!--    发起请假申请-->
    <a-drawer
            title="填写请假信息"
            :width="700"
            :visible="leaveDrawVisible"
            :body-style="{ paddingBottom: '40px' }"
            :footer-style="{ textAlign: 'right' }"
            @close="leaveDrawVisible = false"
    >
        <a-form :model="leaveBill" layout="vertical">
            <a-row>
                <a-form-item label="请假人">
                    <a-input v-model:value="loginUser.username" disabled></a-input>
                </a-form-item>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="标题" v-bind="validateInfos.title">
                        <a-input v-model:value="leaveBill.title" placeholder="请输入标题"/>
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="请假天数">
                        <a-input v-model:value="leaveBill.days" disabled/>
                    </a-form-item>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item label="请假起止时间" v-bind="validateInfos.leaveStart">
                        <a-config-provider :locale="locale">
                            <a-range-picker
                                    v-model:value="startAndEndTime"
                                    :show-time="{ format: 'HH:mm' }"
                                    style="width: 400px"
                                    :disabled-date="disabledDate"
                                    @change="rangeTimeChange"
                                    format="YYYY-MM-DD HH:mm:ss"
                            />
                        </a-config-provider>
                    </a-form-item>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item label="请假原因" name="remark">
                        <a-textarea v-model:value="leaveBill.remark" :rows="5"/>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
        <template #footer>
            <a-space>
                <a-button type="default" @click="leaveDrawVisible = false">取消</a-button>
                <a-button type="primary" @click="leaveApply">申请</a-button>
            </a-space>
        </template>
    </a-drawer>
    <!--    查看请假详情-->
    <a-drawer
            title="请假申请单"
            :width="1000"
            :visible="leaveVisible"
            :body-style="{ paddingBottom: '40px' }"
            :footer-style="{ textAlign: 'right' }"
            @close="leaveVisible = false"
    >
        <a-form :model="drawerData.billInfo" layout="vertical">
            <a-row>
                <a-form-item label="请假申请人">
                    <a-input v-model:value="drawerData.billInfo.username" disabled/>
                </a-form-item>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="标题" name="title">
                        <a-input v-model:value="drawerData.billInfo.title" disabled/>
                    </a-form-item>
                </a-col>
                <a-col :span="6">
                    <a-form-item label="请假天数" name="days">
                        <a-input v-model:value="drawerData.billInfo.days" disabled/>
                    </a-form-item>
                </a-col>
                <a-col :span="6">
                    <a-form-item label="状态" name="status">
                        <a-tag v-if="drawerData.billInfo.status == 2" color="warning">
                            <template #icon>
                                <exclamation-circle-outlined/>
                            </template>
                            被驳回
                        </a-tag>
                        <a-tag v-else-if="drawerData.billInfo.status == 0" color="processing">
                            <template #icon>
                                <sync-outlined :spin="true"/>
                            </template>
                            审批中
                        </a-tag>
                        <a-tag v-else color="success">
                            <template #icon>
                                <check-circle-outlined/>
                            </template>
                            审批通过
                        </a-tag>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item label="请假起止时间">
                        <a-config-provider :locale="locale">
                            <a-range-picker
                                    :disabled="true"
                                    v-model:value="startAndEndTime"
                                    :show-time="{ format: 'HH:mm' }"
                                    style="width: 400px"
                                    :disabled-date="disabledDate"
                                    @change="rangeTimeChange"
                                    format="YYYY-MM-DD HH:mm:ss"
                            />
                        </a-config-provider>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item label="请假原因" name="remark">
                        <a-textarea :disabled="true" v-model:value="drawerData.billInfo.remark" :rows="3"/>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
        <a-list
                item-layout="horizontal"
                size="large"
                style="margin-top: 10px"
                bordered
                :data-source="drawerData.comments"
        >
            <template #header>
                <div>批注列表</div>
            </template>
            <template #renderItem="{ item, index }">
                <a-list-item>
                    <a-list-item-meta>
                        <template #title>
                            {{ item.username }}({{item.roleName}})
                        </template>
                        <template #avatar>
                            <a-avatar :src="item.pic"/>
                        </template>
                        <template #description>{{item.fullMessage}}</template>
                    </a-list-item-meta>
                    <div>
                        {{formatDate(item.time)}}
                    </div>
                </a-list-item>
            </template>
        </a-list>

    </a-drawer>
</template>

<script>
    import {ref, onMounted} from 'vue'
    import axios from 'axios'
    import {Form, message} from 'ant-design-vue'
    import store from '@/store'
    import dayjs from 'dayjs'
    import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
    import {CheckCircleOutlined, CloseCircleOutlined, SyncOutlined} from "@ant-design/icons-vue";

    export default {
        name: "leaveBill",
        components: {
            CloseCircleOutlined,
            SyncOutlined,
            CheckCircleOutlined
        },
        setup() {
            const columns = [
                {
                    title: 'ID',
                    dataIndex: 'id',
                    key: 'id',
                },
                {
                    title: '标题',
                    dataIndex: 'title',
                    key: 'title',
                },
                {
                    title: '天数',
                    dataIndex: 'days',
                    key: 'days',
                },
                {
                    title: '请假时间',
                    dataIndex: 'leaveDate',
                    key: 'leaveDate',
                },
                {
                    title: '审批进度',
                    dataIndex: 'taskName',
                    key: 'taskName',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                },
                {
                    title: '操作',
                    key: 'action',
                }
            ]
            const commentColumns = [
                {
                    title: '时间',
                    dataIndex: 'time',
                    key: 'time',
                },
                {
                    title: '批注人',
                    dataIndex: 'userId',
                    key: 'user',
                },
                {
                    title: '批注信息',
                    dataIndex: 'fullMessage',
                    key: 'fullMessage',
                },
            ]

            const locale = zhCN
            const loginUser = ref({})
            const leaveBill = ref({
                title: '',
                leaveStart: undefined,
                leaveEnd: undefined
            })
            const leaveBillList = ref()
            const pagination = ref({
                current: 1,
                pageSize: 5,
            })
            const pageSizeOptions = ref(['5', '10', '20', '30', '50', '100'])

            const leaveVisible = ref(false)
            const leaveDrawVisible = ref(false)
            const drawerData = ref({})

            const useForm = Form.useForm
            const {validate, validateInfos, resetFields, validateField, rulesRef} = useForm(leaveBill, ref({
                title: [{required: true, message: '请输入标题', trigger: ['change']}],
                leaveStart: [{required: true, message: '请选择请假起止时间', trigger: ['change']}]
            }))

            const disabledDate = current => {
                return current < dayjs().subtract(1, 'days').endOf('day');
            };
            const startAndEndTime = ref([])


            const load = (pageNum) => {
                pagination.value.current = pageNum == 1 ? 1 : pagination.value.current
                axios.get('/leave-bill/queryByUserId/' + loginUser.value.id, {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    leaveBillList.value = rs.data.records
                    pagination.value.total = rs.data.total
                })
            }

            const onChange = (pageNum, pageSize) => {
                pagination.value.current = pageNum
                pagination.value.pageSize = pageSize
                load()
            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/leave-bill/deleteByBillId/' + id).then(rs => {
                    if (rs.data.code == 200) {
                        message.success("删除成功")
                        load(1)
                    } else {
                        message.error(rs.data.message)
                    }
                })
            }

            const checkAuditTrail = (id) => {
                axios.get('process/auditTrail/leave/' + id).then(rs => {
                    drawerData.value = rs.data
                    startAndEndTime.value.push(dayjs(drawerData.value.billInfo.leaveStart))
                    startAndEndTime.value.push(dayjs(drawerData.value.billInfo.leaveEnd))
                    leaveVisible.value = true
                })
            }

            const openLeaveDraw = () => {
                resetFields()
                startAndEndTime.value = []
                leaveDrawVisible.value = true
            }

            const rangeTimeChange = (dates, dateStrings) => {
                // console.log("dates",dates)
                // console.log("dateStrings",dateStrings)
                let minutes = dates[1].diff(dates[0], 'minutes')
                leaveBill.value.days = Number(minutes / 60 / 24).toFixed(1)
                leaveBill.value.leaveStart = dates[0]
                leaveBill.value.leaveEnd = dates[1]
            }

            const leaveApply = () => {
                validate().then(() => {
                    leaveBill.value.userId = loginUser.value.id
                    leaveBill.value.leaveDate = dayjs()
                    console.log("请假单信息：", leaveBill.value)

                    console.log("校验通过")
                    axios.post('leaveProcess/startProcess', leaveBill.value).then(rs => {
                        if (rs.code == 200) {
                            message.success("成功发起请假申请，请您耐心等待审批")
                            leaveDrawVisible.value = false
                            load()
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch((e) => {
                    console.log("校验失败", e)
                })
            }

            const formatDate = (time) => {
                return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
            }

            onMounted(() => {
                loginUser.value = store.state.user
                load()
            })
            return {
                columns,
                commentColumns,
                pagination,
                onChange,
                load,
                okDelete,
                leaveBill,
                leaveBillList,
                checkAuditTrail,
                leaveVisible,
                drawerData,
                locale,
                formatDate,
                pageSizeOptions,
                openLeaveDraw,
                leaveDrawVisible,
                leaveApply,
                loginUser,
                disabledDate,
                startAndEndTime,
                rangeTimeChange,
                validateInfos
            }
        }
    }
</script>

<style scoped>
    .cardContent {
        background: #fff;
        margin: 10px 10px 0 10px;
        padding: 15px;
    }
</style>